<template>
<div class="top-menu">
  <el-menu :default-active="activeIndex" mode="horizontal">
    <template v-for="(item,index) in items">
      <el-menu-item :index="item.code+''" @click.native="openMenu(item)" :key="index">
        <template slot="title">
          <i :class="item.icon"></i>
          <span>  {{item.name}}</span>
        </template>
      </el-menu-item>
    </template>
  </el-menu>
</div>
</template>

<script>
import {
  mapGetters
} from "vuex";
export default {
  name: "top-menu",
  data() {
    return {
      activeIndex: '',
      items: []
    };
  },
  inject: ["index"],
  created() {
    this.getMenu();
  },
  computed: {
    ...mapGetters([ "topMenu"])
  },
  methods: {
    openMenu(item) {
      this.$store.commit('SET_TOP_MENU', item)
      this.index.openMenu(item);
      if (item.router){
        this.$router.push({
          path: item.router
        },()=>{},()=>{});
      }
    },
    getMenu() {
      //获取所有按钮CODE
      this.$store.dispatch("GetBtnCode");
      //获取所有顶部菜单
      this.$store.dispatch("GetTopMenu").then(res => {
        this.items = res;
        if (this.topMenu){
          this.activeIndex = this.topMenu.code;
          this.openMenu(this.topMenu)
        }else {
          this.index.openMenu()
        }
      });
    }
  }
};
</script>
